package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.been.SMSResult;
import com.superfish.cutieshop.http.HttpError;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonCheckMobile;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.MessageHandlerList;
import com.superfish.cutieshop.utils.TimeUtils;
import com.superfish.cutieshop.utils.ValidateUtil;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by lmh on 15/10/15.
 */

@ContentView(R.layout.activity_resetpassword1)
public class ResetPassword1Activity extends BaseActivity {
    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.et_mobile)
    private EditText et_mobile;
    @ViewInject(R.id.et_code)
    private EditText et_code;
    @ViewInject(R.id.tv_getcode)
    private TextView tv_getcode;
    private String phoneNumber;

    // 倒计时时间
    private int time = BaseConfig.RETRY_INTERVAL;

    public static void open(Activity act) {
        Intent i = new Intent(act, ResetPassword1Activity.class);
        open(act, i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar();
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }

    public void initToolBar() {
        mToolbar.setTitle("");
        setAppTitle(R.string.title_resetpassword1);
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
    }

    @OnClick(R.id.tv_getcode)
    public void onClickGetCode(View view) {
        phoneNumber = et_mobile.getText().toString();
        String str = ValidateUtil.valPhone(phoneNumber, this);
        if (!TextUtils.isEmpty(str)) {
            et_mobile.setError(str);
            return;
        }
        freezeMobile();
        fetchCheckMobile(phoneNumber);

    }

    private void freezeMobile() {
        LogTest.lmh("冻结");
        et_mobile.setEnabled(false);
        tv_getcode.setEnabled(false);
        et_mobile.setTextColor(getResources().getColor(R.color.y1_30));
        tv_getcode.setText(getResources().getString(R.string.register_checkmobile));
    }

    private void thawMobile() {
        LogTest.lmh("解冻");
        et_mobile.setEnabled(true);
        tv_getcode.setEnabled(true);
        et_mobile.setTextColor(getResources().getColor(R.color.y1));
        tv_getcode.setText(getResources().getString(R.string.sms_get_verify));
    }

    private void fetchCheckMobile(String mobile) {
        ZokeParams params = HttpParams.checkMobile(mHashCode, mobile);
        HttpStores.getInstense().login(params);
    }

    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        ResponseInfo result = (ResponseInfo) out.getResult();
        LogTest.lmh("result=" + result.result);
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.check_mobile)) {
            String json = (String) result.result;
            GsonCheckMobile gsonCheckMobile = new GsonCheckMobile().fromJson(json);
            if (gsonCheckMobile.info == null || gsonCheckMobile.error_code != 0) {
                //失败
                thawMobile();
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            if (gsonCheckMobile.info.mobile == null || !gsonCheckMobile.info.mobile.equals(phoneNumber)) {
                thawMobile();
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            if (gsonCheckMobile.info.check.equals("0")) {
                //没注册
                thawMobile();
                et_mobile.setError(getResources().getString(R.string.resetpassword_phonenoregisted));
            } else {
                //已注册
                SMSSDK.getVerificationCode(BaseConfig.DEFAULT_COUNTRY_ID, et_mobile.getText().toString().trim());
                startCountDown();
            }
            return;
        }
    }

    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        HttpError error = (HttpError) out.getResult();
        LogTest.lmh("error=" + error.s);
        CutieToast.show(this, getResources().getString(R.string.global_error_internet));
    }

    /**
     * 倒计时接口
     */
    private Runnable timeRunnable = new Runnable() {

        @Override
        public void run() {
            if (time == 0) {
                time = BaseConfig.RETRY_INTERVAL;
                stopCountDown();
            } else {
                String again = getString(R.string.sms_get_verify_again);
                String aginTime = String.format(again, "(" + time + ")");
                tv_getcode.setText(aginTime);
//                tv_getcode.setEnabled(false);
                mHandler.postDelayed(this, 1000);
                time--;
            }
        }
    };

    /**
     * 倒数计时开始
     */
    private void startCountDown() {
        mHandler.post(timeRunnable);
    }

    /**
     * 停止计时
     */
    private void stopCountDown() {
        thawMobile();
        mHandler.removeCallbacks(timeRunnable);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_resetpassword1, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            phoneNumber = et_mobile.getText().toString();
            String str_mobile = ValidateUtil.valPhone(phoneNumber, this);
            if (!TextUtils.isEmpty(str_mobile)) {
                et_mobile.setError(str_mobile);
                return true;
            }

            if (TextUtils.isEmpty(et_code.getText().toString())) {
                et_code.setError(getResources().getString(R.string.register_codenonull));
                return true;
            }
            LogTest.lmh("即将开始验证---------");
            SMSSDK.submitVerificationCode(BaseConfig.DEFAULT_COUNTRY_ID, phoneNumber, et_code.getText().toString());
//            ResetPassword2Activity.open(this, et_mobile.getText().toString());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    EventHandler eh = new EventHandler() {

        @Override
        public void afterEvent(int event, int result, Object data) {
            LogTest.lmh("afterEvent-event:" + event);
            LogTest.lmh("afterEvent-result:" + result);
            LogTest.lmh("afterEvent-data:" + data);
            SMSResult r = new SMSResult();
            r.event = event;
            r.result = result;
            r.data = data;
            MessageHandlerList.sendMessage(ResetPassword1Activity.class, BaseConfig.MessageCode.ON_SMS_CALLBACK, r);
        }
    };

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what) {
            case BaseConfig.MessageCode.ON_SMS_CALLBACK:
                SMSResult r = (SMSResult) msg.obj;
                int event = r.event;
                int result = r.result;
                Object data = r.data;
                LogTest.lmh("event=" + event);
                LogTest.lmh("result=" + result);
                LogTest.lmh("data=" + data.toString());
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //短信注册成功后，返回MainActivity,然后提示新好友
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
//                        ResetPassword2Activity.open(this);
                        ResetPassword2Activity.open(this, phoneNumber);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        CutieToast.show(this, getResources().getString(R.string.register_sendcode));
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表
                    }
                } else {
                    CutieToast.show(this, getResources().getString(R.string.register_codeerror));
                }
                break;
            case BaseConfig.MessageCode.ON_RESETPASSWORD_COMPLETE:
                this.finish();
                break;
            default:
                break;
        }
    }
}
